<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <!-- 租户 -->
      <el-form-item label="租户" prop="rechargeTenantId">
        <el-select
          v-model="formData.rechargeTenantId"
          placeholder="请选择租户"
          clearable
          filterable
          class="!w-260px"
        >
          <el-option
            v-for="opt in tenantOptions"
            :key="opt.value"
            :label="opt.label"
            :value="opt.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="过滤网关" prop="filterName">
        <el-input v-model="formData.filterName" placeholder="请输入过滤网关" />
      </el-form-item>

      <el-form-item label="密钥" prop="appSecret">
        <el-input v-model="formData.appSecret" placeholder="请输入密钥" />
      </el-form-item>

      <el-form-item label="到期时间" prop="expireTime">
        <el-date-picker
          v-model="formData.expireTime"
          type="datetime"
          placeholder="请选择过期时间"
          clearable
          value-format="x"
          format="YYYY-MM-DD HH:mm:ss"
          class="!w-260px"
        />
      </el-form-item>

      <!-- 产品权限：多选，保存为逗号拼接 -->
      <el-form-item label="产品权限" prop="productPermissions">
        <el-select
          v-model="formData.productPermissions"
          multiple
          collapse-tags
          collapse-tags-tooltip
          placeholder="请选择产品权限"
          class="!w-260px"
        >
          <el-option
            v-for="opt in reqTypeOptions"
            :key="opt.value"
            :label="opt.label"
            :value="opt.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="启用状态" prop="enabled">
        <!-- 用 label 绑定 1/0，再在提交时转 boolean -->
        <el-radio-group v-model="formData.enabled">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">停用</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 新增：随路数据 attach（可填字符串或 JSON 字符串） -->
      <el-form-item label="随路数据" prop="attach">
        <el-input
          v-model="formData.attach"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 8 }"
          placeholder='可填写任意随路数据；若为对象，请粘贴 JSON，比如：{"k":"v"}'
          class="!w-520px"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { SecretAccountApi, type SecretAccount } from '@/api/vos/secretaccount'
import * as TenantApi from '@/api/system/tenant'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'

defineOptions({ name: 'SecretAccountForm' })

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref<'create' | 'update'>('create')

/** 字典：产品权限 */
const reqTypeOptions = getStrDictOptions(DICT_TYPE.REQUEST_TYPE)

/** 租户下拉 */
type TenantOption = { value: number; label: string }
const tenantOptions = ref<TenantOption[]>([])
const loadTenants = async () => {
  const res = await TenantApi.getTenantList()
  const arr = Array.isArray(res) ? res : (res?.list ?? [])
  tenantOptions.value = arr.map((it: any) => ({
    value: Number(it.id),
    label: it.name || `租户#${it.id}`
  }))
}

/** 表单（用 any 规避 Volar 对 value-format="x" 的类型推断冲突） */
const formRef = ref()
const formData = ref<any>({
  id: undefined,
  rechargeTenantId: undefined,
  filterName: undefined,
  appSecret: undefined,
  expireTime: null as number | null, // 毫秒时间戳（number|null）
  productPermissions: [] as string[],
  enabled: 1,
  attach: '' as string // 新增字段：随路数据（统一以字符串提交）
})

/** 校验 */
const formRules = reactive({
  rechargeTenantId: [{ required: true, message: '租户不能为空', trigger: 'change' }],
  appSecret: [{ required: true, message: '密钥不能为空', trigger: 'blur' }],
  enabled: [{ required: true, message: '请选择启用状态', trigger: 'change' }]
  // attach 为可选项，不做强校验
})

/** 工具：任意输入 -> 毫秒 number|null */
const toMs = (v: any): number | null => {
  if (v == null || v === '') return null
  if (typeof v === 'number') return v < 1e12 ? v * 1000 : v // 秒 -> 毫秒
  if (typeof v === 'string') {
    const s = v.trim()
    if (/^\d{10,13}$/.test(s)) {
      const n = Number(s)
      return s.length === 10 ? n * 1000 : n
    }
    const d = dayjs(s)
    return d.isValid() ? d.valueOf() : null
  }
  return null
}

/** 工具：把后端 attach 值规整为字符串供编辑（对象 -> pretty JSON） */
const toAttachString = (v: any): string => {
  if (v == null) return ''
  if (typeof v === 'string') return v
  try {
    return JSON.stringify(v, null, 2)
  } catch {
    return String(v)
  }
}

/** 打开弹窗 */
const open = async (type: 'create' | 'update', id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  await loadTenants()

  if (id) {
    formLoading.value = true
    try {
      const data: any = await SecretAccountApi.getSecretAccount(id)

      if (data?.rechargeTenantId != null) data.rechargeTenantId = Number(data.rechargeTenantId)

      // 启用状态兼容后端各种类型 -> 1/0
      if (typeof data?.enabled === 'boolean') data.enabled = data.enabled ? 1 : 0
      else if (typeof data?.enabled === 'string') data.enabled = Number(data.enabled) ? 1 : 0
      else if (typeof data?.enabled === 'number') data.enabled = data.enabled ? 1 : 0
      else data.enabled = 0
      // 统一把 expireTime 转为毫秒 number（避免被当成"1756-..."的字符串日期解析）
      data.expireTime = toMs(data?.expireTime)

      // 产品权限：后端逗号字符串 -> 数组
      if (data?.productPermissions) {
        data.productPermissions = String(data.productPermissions)
          .split(',')
          .map((s: string) => s.trim())
          .filter(Boolean)
      } else {
        data.productPermissions = []
      }

      formData.value = {
        id: data.id,
        rechargeTenantId: data.rechargeTenantId,
        filterName: data.filterName,
        appSecret: data.appSecret,
        expireTime: data.expireTime,
        productPermissions: data.productPermissions,
        enabled: data.enabled,
        attach: toAttachString(data.attach) // 加载 attach
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

/** 提交 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  await formRef.value?.validate()
  formLoading.value = true
  try {
    const payload: any = { ...formData.value }

    // 1/0 -> boolean
    payload.enabled = payload.enabled === 1

    if (payload.rechargeTenantId != null) payload.rechargeTenantId = Number(payload.rechargeTenantId)

    // 确保为 number|null 的毫秒
    payload.expireTime = toMs(payload.expireTime)

    // 产品权限：数组 -> 逗号
    if (Array.isArray(payload.productPermissions)) {
      payload.productPermissions = payload.productPermissions.join(',')
    }

    // attach：统一以字符串提交（后端如需要 JSON，可自行解析）
    if (payload.attach == null) payload.attach = ''
    else if (typeof payload.attach !== 'string') payload.attach = String(payload.attach)
    else payload.attach = payload.attach.trim()

    if (formType.value === 'create') {
      await SecretAccountApi.createSecretAccount(payload as SecretAccount)
      message.success(t('common.createSuccess'))
    } else {
      await SecretAccountApi.updateSecretAccount(payload as SecretAccount)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    rechargeTenantId: undefined,
    filterName: undefined,
    appSecret: undefined,
    expireTime: null,
    productPermissions: [],
    enabled: 1,
    attach: ''
  }
  formRef.value?.resetFields?.()
}
</script>
